package utils

import (
	"bytes"
	"os/exec"
	"strings"
)

// WinCmd 对应Java中的WinCmd
type WinCmd struct {
	originalCommandMsg string
	output             string
	exitValue          int
}

// GetInstance 创建新的WinCmd实例
func GetInstance() *WinCmd {
	return &WinCmd{}
}

// GetExitValue 获取命令退出码
func (w *WinCmd) GetExitValue() (int, error) {
	if w.originalCommandMsg == "" {
		return 0, nil
	}
	return w.exitValue, nil
}

// GetOutput 获取命令输出
func (w *WinCmd) GetOutput() (string, error) {
	if w.originalCommandMsg == "" {
		return "", nil
	}
	return w.output, nil
}

// Execute 执行命令
func (w *WinCmd) Execute(command string) (*WinCmd, error) {
	w.originalCommandMsg = command
	cmd := exec.Command("cmd", "/C", command)
	var out bytes.Buffer
	cmd.Stdout = &out
	err := cmd.Run()
	if err != nil {
		if exitError, ok := err.(*exec.ExitError); ok {
			w.exitValue = exitError.ExitCode()
		}
		return w, err
	}
	w.output = strings.TrimSpace(out.String())
	w.exitValue = 0
	return w, nil
}
